<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    v-model="visible"
    form
    :width="640"
    :title="isUpdate ? '编辑用户' : '新增用户'"
    @open="handleOpen"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent=""
    >
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="用户账号" prop="username">
            <el-input
              v-model="form.username"
              clearable
              :maxlength="20"
              placeholder="请输入用户账号"
            />
          </el-form-item>
          <el-form-item label="用户名" prop="nickname">
            <el-input
              v-model="form.nickname"
              clearable
              :maxlength="20"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <dict-data v-model="form.sex" code="sex" placeholder="请选择性别" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="form.phone"
              clearable
              :maxlength="11"
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              clearable
              :maxlength="100"
              placeholder="请输入邮箱"
            />
          </el-form-item>
          <el-form-item v-if="!isUpdate" label="登录密码" prop="password">
            <el-input
              v-model="form.password"
              show-password
              type="password"
              :maxlength="20"
              placeholder="请输入登录密码"
            />
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input
              v-model="form.introduction"
              type="textarea"
              :rows="3"
              :maxlength="200"
              placeholder="请输入个人简介"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { addUser, checkExistence, updateUser } from '@/api/system/user'
import { useFormData } from '@/utils/use-form-data'
import { EleMessage, emailReg, phoneReg } from 'ele-admin-plus/es'
import { nextTick, reactive, ref } from 'vue'

const props = defineProps({
  /** 修改回显的数据 */
  data: Object,
  /** 新增时机构id */
  organizationId: Number,
  /** 指定机构下拉数据 */
  organizationData: Array,
})

const emit = defineEmits(['done'])

/** 弹窗是否打开 */
const visible = defineModel({ type: Boolean })

/** 是否是修改 */
const isUpdate = ref(false)

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

/** 表单数据 */
const [form, resetFields, assignFields] = useFormData({
  userId: void 0,
  organizationId: void 0,
  username: '',
  nickname: '',
  sex: void 0,
  roles: [],
  email: '',
  phone: '',
  password: '',
  introduction: '',
})

/** 表单验证规则 */
const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户账号',
      type: 'string',
      trigger: 'blur',
    },
    {
      min: 4,
      message: '账号长度最少为4位',
      type: 'string',
      trigger: 'blur',
    },
    {
      type: 'string',
      trigger: 'blur',
      validator: (_rule, value, callback) => {
        checkExistence('username', value, props.data?.userId)
          .then(() => {
            callback(new Error('账号已经存在'))
          })
          .catch(() => {
            callback()
          })
      },
    },
  ],
  nickname: [
    {
      required: true,
      message: '请输入用户名',
      type: 'string',
      trigger: 'blur',
    },
  ],
  sex: [
    {
      required: true,
      message: '请选择性别',
      type: 'string',
      trigger: 'change',
    },
  ],
  roles: [
    {
      required: true,
      message: '请选择角色',
      type: 'array',
      trigger: 'change',
    },
  ],
  email: [
    {
      pattern: emailReg,
      message: '邮箱格式不正确',
      type: 'string',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入登录密码',
      type: 'string',
      trigger: 'blur',
    },
    {
      type: 'string',
      trigger: 'blur',
      validator: (_rule, value, callback) => {
        if (isUpdate.value || /^\S{5,18}$/.test(value)) {
          return callback()
        }
        callback(new Error('密码必须为5-18位非空白字符'))
      },
    },
  ],
  phone: [
    {
      pattern: phoneReg,
      message: '手机号格式不正确',
      type: 'string',
      trigger: 'blur',
    },
  ],
})

/** 关闭弹窗 */
function handleCancel() {
  visible.value = false
}

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      return
    }
    loading.value = true
    const saveOrUpdate = isUpdate.value ? updateUser : addUser
    saveOrUpdate(form)
      .then((msg) => {
        loading.value = false
        EleMessage.success(msg)
        handleCancel()
        emit('done')
      })
      .catch((e) => {
        loading.value = false
        EleMessage.error(e.message)
      })
  })
}

/** 弹窗打开事件 */
function handleOpen() {
  if (props.data) {
    assignFields({ ...props.data, password: '' })
    isUpdate.value = true
  }
  else {
    resetFields()
    form.organizationId = props.organizationId
    isUpdate.value = false
  }
  nextTick(() => {
    nextTick(() => {
      formRef.value?.clearValidate?.()
    })
  })
}
</script>
